//
//  UITextView+YLExtension.swift
//  QingLiuSwift
//
//  Created by xyanl on 2023/9/4.
//

import UIKit

extension UITextView {
    
    /// 限制textField输入
    public func limitInputWithPattern(pattern: String, _ limitCount: Int = -1) {
        // 非markedText才继续往下处理
        guard let _: UITextRange = self.markedTextRange else {
            // 当前光标的位置（后面会对其做修改）
            let cursorPostion = self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
            // 替换后的字符串
            var str = ""
            if pattern == "" {
                str = self.text!
            } else {
                str = self.text!.regularReplace(pattern: pattern, with: "")
            }
            // 如果长度超过限制则直接截断
            if limitCount >= 0, str.count > limitCount {
                str = String(str.prefix(limitCount))
            }
            self.text = str
            // 让光标停留在正确位置
            let targetPostion = self.position(from: self.endOfDocument, offset: cursorPostion)!
            self.selectedTextRange = self.textRange(from: targetPostion, to: targetPostion)
            return
        }
    }
 
}

extension String {
 
    // 使用正则表达式替换
    func regularReplace(pattern: String, with: String, options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, self.count), withTemplate: with)
    }
 
}

extension UITextView {
    
    private static let kPlaceholderTag = 20240202
    
    var placeholder: String {
        set {
            if let lb = viewWithTag(UITextView.kPlaceholderTag) as? UILabel {
                lb.text = newValue
            } else {
                let lb = UILabel()
                lb.tag = UITextView.kPlaceholderTag
                lb.font = font
                lb.numberOfLines = 0
                lb.textColor = .lightGray
                lb.text = newValue
                lb.sizeToFit()
                addSubview(lb)
                setValue(lb, forKey: "_placeholderLabel")
            }
        }
        get {
            let lb = value(forKey: "_placeholderLabel") as? UILabel
            return lb?.text ?? ""
        }
    }
}
